<?php

namespace app\models;

use Yii;

/**
 * @property mixed branch
 * @property mixed chargeUser
 */
class Department extends \yii\db\ActiveRecord
{
    public function rules()
    {
        return [
            [['name', 'branch_id'], 'required'],
            [['branch_id','user_id'], 'integer'],
            [['name'], 'string', 'max' => 40],
        ];
    }

    public function extraFields()
    {
        $fields['branch_name'] = function (){
            return $this->branch->name;
        };
        $fields['charge_user_name'] = function (){
            if($this->chargeUser)
                return $this->chargeUser->username;
            return null;
        };
        return $fields;
    }

//    public function save($runValidation = true, $attributeNames = null)
//    {
//        $result = parent::save($runValidation, $attributeNames); // TODO: Change the autogenerated stub.
//        if($result) {
//            $departmentList  = Department::find()->asArray()->all();
//            foreach ($departmentList as $department){
//                Yii::$app->cache->set($department['name'], $department['id']);
//            }
//        }
//        return $result;
//    }
    /**
     * @return mixed
     */
    public static function getOrSet(){
        return Yii::$app->cache->getOrSet('departments', function () {
            return self::find()->asArray()->all();
        });
    }

    /**
     * @param $name
     * @return bool
     */
    public static function getDepartmentByName($name){
        $departments = self::getOrSet();
        foreach ($departments as $department){
            if($department['name'] === $name){
                return $department;
            }
        }
        return false;
    }

    public function getBranch(){
        return $this->hasOne(Branch::class,['id'=>'branch_id']);
    }

    public function getChargeUser(){
        return $this->hasOne(User::class,['id'=>'user_id']);
    }

    public function getUsers(){
        return $this->hasMany(User::class,['department_id'=>'id']);
    }
}
